import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

/*使用EventBus事件总线
* 1.创建全局EventBus对象
* */
final eventBus = EventBus();

// 定义事件类
class Event {
  String name;
  int age;

  Event(this.name, this.age);
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '跨组件通讯',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('跨组件通讯'),
        ),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ButtonWidget(),
          TextWidget(),
        ],
      ),
    );
  }
}

// ButtonWidget、TextWidget是兄弟组件，点击按钮Text要做出改变
// 常规做法是在Text中定义改变的方法，然后传入GlobalKey调用
// 如果嵌套层级过多，这种方式就会很麻烦，使用EventBus轻松解决
class ButtonWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        // 发送事件
        eventBus.fire(Event("fauks", 19));
      },
      child: Text('click'),
    );
  }
}

class TextWidget extends StatefulWidget {
  @override
  _TextWidgetState createState() => _TextWidgetState();
}

class _TextWidgetState extends State<TextWidget> {
  String _message = "wait...";

  @override
  void initState() {
    super.initState();
    // 监听事件
    eventBus.on().listen((event) {
      setState(() {
        _message = event.toString();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      '$_message',
      style: TextStyle(fontSize: 28),
    );
  }
}
